package com.nsgf.library.widget.prckerview;

/**
 * Created by Android研发 on 2018/12/24.
 */


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.PermissionRequest;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.nsgf.library.R;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.skjz.utils.Kits;


/**
 * The type My web view.
 */
public class MyWebView extends RelativeLayout {
    /**
     * The Content wv.
     */
    protected WebView contentWv;
    /**
     * The Lodding bar.
     */
    protected ProgressBar loddingBar;
    /**
     * The Root.
     */
    private View root;
    /**
     * The Context.
     */
    private Context context;
    /**
     * The Is show lodding bar.
     */
    private boolean isShowLoddingBar = true;

    /**
     * Instantiates a new My web view.
     *
     * @param context the context
     * @param attrs   the attrs
     */
    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    /**
     * Instantiates a new My web view.
     *
     * @param context the context
     */
    public MyWebView(Context context) {
        super(context);
        this.context = context;
    }

    /**
     * Instantiates a new My web view.
     *
     * @param arg0 the arg 0
     * @param arg1 the arg 1
     * @param arg2 the arg 2
     */
    public MyWebView(Context arg0, AttributeSet arg1, int arg2) {
        super(arg0, arg1, arg2);

        init();
    }

    @SuppressLint("JavascriptInterface")
    public void addJavascriptInterface(Object object, String name) {
        contentWv.addJavascriptInterface(object, name);
    }

    public void reload() {
        contentWv.reload();
    }

    /**
     * Init.
     */
    private void init() {
        root = inflate(this.context, R.layout.my_webview, this);
        contentWv = root.findViewById(R.id.my_wv_content_webview);
//        loddingBar = root.findViewById(R.id.my_wv_lodding_progressbar);
        configWebView();


        contentWv.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,

                                        long contentLength) {
                Log.i("tag", "url=" + url);
                Log.i("tag", "userAgent=" + userAgent);
                Log.i("tag", "contentDisposition=" + contentDisposition);
                Log.i("tag", "mimetype=" + mimetype);
                Log.i("tag", "contentLength=" + contentLength);
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
                contentWv.reload();
            }
        });
    }

    /**
     * Config web view.
     */
    private void configWebView() {
        WebSettings settings = contentWv.getSettings();
        settings.setUseWideViewPort(false);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setJavaScriptEnabled(true);

        // 允许混合内容（HTTPS页面加载HTTP资源）
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        
        // 允许不安全内容
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);

        settings.setDomStorageEnabled(true);//设置适应Html5 //重点是这个设置
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE); //设置缓存

        contentWv.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (request.getUrl().toString().startsWith("wtloginmqq://ptlogin/qlogin")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getUrl().toString()));
                    context.startActivity(intent);
                    return true;
                } else if (request.getUrl().toString().startsWith("mqq")) {

                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getUrl().toString()));
                    context.startActivity(intent);
                    return super.shouldOverrideUrlLoading(view, request.getUrl().toString());
                } else if (request.getUrl().toString().startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(request.getUrl().toString()));
                    //Android6.0以后的动态获取打电话权限
                    if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
                        context.startActivity(intent);
                        //这个超连接,java已经处理了，webview不要处理
                        return true;
                    } else {
                        //申请权限
                        ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.CALL_PHONE}, 1);
                        return true;
                    }
                }
                return super.shouldOverrideUrlLoading(view, request.getUrl().toString());

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (loddingBar == null) return;

                if (isShowLoddingBar) loddingBar.setVisibility(View.VISIBLE);
                else loddingBar.setVisibility(View.GONE);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (loddingBar == null) return;
                loddingBar.setVisibility(View.GONE);
                String title = view.getTitle();
                if (textViewTitle != null)
                    textViewTitle.setText(title);
            }
        });
        contentWv.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onPermissionRequest(PermissionRequest request) {
//                super.onPermissionRequest(request);
                // 检查请求的权限类型
                String[] resources = request.getResources();
                boolean shouldGrant = true; // 根据实际情况决定是否授予权限

                if (shouldGrant) {
                    // 授予权限
                    request.grant(resources);
                } else {
                    // 拒绝权限
                    request.deny();
                }

            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (loddingBar == null) return;
                loddingBar.setProgress(newProgress);
            }
        });
    }

    /**
     * Sets lodding bar status.
     *
     * @param isShow the is show
     */
    protected void setLoddingBarStatus(boolean isShow) {
        loddingBar.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    /**
     * Gets web settings.
     *
     * @return the web settings
     */
    protected WebSettings getWebSettings() {
        return contentWv.getSettings();
    }

    /**
     * Gets content wv.
     *
     * @return the content wv
     */
    public WebView getContentWv() {
        return contentWv;
    }

    public WebView getWebView() {
        return contentWv;
    }

    /**
     * Gets lodding bar.
     *
     * @return the lodding bar
     */
    public ProgressBar getLoddingBar() {
        return loddingBar;
    }

    /**
     * Destroy.
     */
    public void destroy() {
        if (contentWv == null) return;
        contentWv.removeAllViews();
        contentWv.destroy();
    }

    /**
     * Load url.
     *
     * @param url the url
     */
    public void loadUrl(String url) {
        if (contentWv == null) return;

        if (!StringUtil.isEmpty(url)) {
            contentWv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
            CookieSyncManager.createInstance(contentWv.getContext());

            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setCookie(url, "token=" + UserInfo.getInstance().getTokenValue());
            cookieManager.setCookie(url, "tokenName=" + UserInfo.getInstance().getTokenName());
            cookieManager.setCookie(url, "projectCode=" + UserInfo.getInstance().getProjectCode());
        }
        contentWv.loadUrl(url);
        Log.e("======================", url);
    }

    TextView textViewTitle;

    /**
     * Load url.
     *
     * @param url the url
     */
    public void loadUrl(String url, TextView textView) {
        if (contentWv == null) return;
        contentWv.loadUrl(url);
        textViewTitle = textView;
    }

    /**
     * Can go back boolean.
     *
     * @return the boolean
     */
    public boolean canGoBack() {
        return contentWv.canGoBack();
    }

    /**
     * Go back.
     */
    public void goBack() {
        contentWv.goBack();
    }
}

